<template>
    <div class="server-container">
        <h1>服务端</h1>

        <!-- 二维码生成区域 -->
        <div class="qr-code-section">
            <h3>手机客户端访问二维码:</h3>
            <div ref="qrCodeRef"></div>
            <p>或访问: {{ clientUrl }}</p>
        </div>

        <div class="current-input">
            <h3>当前输入内容:</h3>
            <div class="content-box">{{ currentContent }}</div>
            <button @click="copyContent">复制并保存</button>
        </div>

        <div class="history-list">
            <h3>历史记录:</h3>
            <ul>
                <li v-for="item in history" :key="item.id">
                    {{ item.content }}
                    <small>{{ new Date(item.created_at).toLocaleString() }}</small>
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import { connectWebSocket } from '../shared/websocket'
import { getHistory } from '../../db'
import QRCode from 'qrcode'
import clipboard from 'clipboardy'

export default {
    data() {
        return {
            currentContent: '',
            history: [],
            ws: null,
            clientUrl: ''
        }
    },
    async mounted() {
        this.loadHistory()

        // 监听主进程发送的客户端URL
        window.electronAPI?.onClientUrl((url) => {
            this.clientUrl = url
            this.generateQRCode(url)
        })

        this.ws = connectWebSocket(`ws://${window.location.hostname}:3600`, (data) => {
            if (data.type === 'input') {
                this.currentContent = data.content
            }
        })
    },
    methods: {
        async loadHistory() {
            getHistory((rows) => {
                this.history = rows
            })
        },
        generateQRCode(text) {
            QRCode.toCanvas(this.$refs.qrCodeRef, text, { width: 200 }, (error) => {
                if (error) console.error('生成二维码失败:', error)
            })
        },
        async copyContent() {
            if (!this.currentContent) return

            try {
                // 尝试使用clipboardy复制
                await clipboard.write(this.currentContent)

                // 发送保存请求
                if (this.ws) {
                    this.ws.send(JSON.stringify({
                        type: 'copy',
                        content: this.currentContent
                    }))
                }

                // 更新本地历史记录
                this.history.unshift({
                    id: Date.now(),
                    content: this.currentContent,
                    created_at: new Date().toISOString()
                })

                alert('复制成功!')
            } catch (error) {
                console.error('复制失败:', error)
                // 备用方案：使用execCommand
                const textarea = document.createElement('textarea')
                textarea.value = this.currentContent
                document.body.appendChild(textarea)
                textarea.select()
                try {
                    document.execCommand('copy')
                    alert('复制成功! (备用方法)')
                } catch (err) {
                    console.error('备用复制方法失败:', err)
                    alert('复制失败，请手动复制内容')
                } finally {
                    document.body.removeChild(textarea)
                }
            }
        }
    },
    beforeUnmount() {
        if (this.ws) {
            this.ws.close()
        }
    }
}
</script>

<style>
/* 原有样式基础上增加二维码区域样式 */
.qr-code-section {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px dashed #ccc;
    border-radius: 5px;
    text-align: center;
}

.qr-code-section h3 {
    margin-top: 0;
}

.qr-code-section p {
    word-break: break-all;
    font-size: 12px;
    color: #666;
}

/* 其他原有样式保持不变 */
</style>